<template>
  <div class="duty-management bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">设备信息</h2>




    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchDutyRecords" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">新增</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <el-button @click="openImportDialog">导入</el-button>
      <el-button @click="exportData(dutyRecords, '设备信息', selectedIds)">导出</el-button>
    </div>

    <!-- Data Table -->
    <el-table v-loading="loading" :data="displayedDutyRecords" @selection-change="handleSelectionChange"
      style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
      :row-key="rowKey">
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column prop="ID" label="序号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="PARK_CODE" label="园区编码" header-align="center" align="center"></el-table-column>
      <el-table-column prop="COMPANY_CODE" label="企业编码" header-align="center" align="center"></el-table-column>
      <el-table-column prop="EQUIPMENT_CODE" label="设备编号" header-align="center" align="center">
      </el-table-column>
      <el-table-column prop="EQUIPMENT_NAME" label="设备名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="EQUIPMENT_LOCATION" label="设备位置" header-align="center" align="center"></el-table-column>
      <el-table-column prop="LONGITUDE" label="经度" header-align="center" align="center"></el-table-column>
      <el-table-column prop="LATITUDE" label="纬度" header-align="center" align="center"></el-table-column>
      <el-table-column prop="EQUIPMENT_TYPE" label="设备类型" header-align="center" align="center"></el-table-column>
      <el-table-column prop="EQUIPMENT_STATUS" label="设备状态" header-align="center" align="center">
      </el-table-column>
      <el-table-column prop="EQUIPMENT_FACTORY" label="生产厂家" header-align="center" align="center">
      </el-table-column>
      <el-table-column prop="EQUIPMENT_MODEL" label="型号" header-align="center" align="center"></el-table-column>
      <el-table-column label="操作" header-align="center" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editDutyRecord(scope.row)" link>编辑</el-button>
          <!-- <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- Pagination -->
    <Pagination v-if="dutyRecords.length" :tableData="dutyRecords" @alltabledata="alltabledata" />
    <!-- Add Dialog -->
    <el-dialog width="600px" class="dialog-from" v-model="isAddDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'"
      destroy-on-close align-center :before-close="closeAddDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-6">
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">园区编码：</label>
              <el-input type="text" v-model="newDutyRecord.PARK_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">企业编码：</label>
              <el-input type="text" v-model="newDutyRecord.COMPANY_CODE" required />

            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">设备编号：</label>
              <el-input type="text" v-model="newDutyRecord.EQUIPMENT_CODE" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">设备名称：</label>
              <el-input type="text" v-model="newDutyRecord.EQUIPMENT_NAME" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">设备位置：</label>
              <el-input type="text" v-model="newDutyRecord.EQUIPMENT_LOCATION" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">经度：</label>
              <el-input type="text" v-model="newDutyRecord.LONGITUDE" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">纬度：</label>
              <el-input type="text" v-model="newDutyRecord.LATITUDE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">设备类型：</label>
              <el-select v-model="newDutyRecord.EQUIPMENT_TYPE" placeholder="请选择" clearable>
                <el-option label="感知设备" value="感知设备" />

              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">设备状态：</label>
              <el-select v-model="newDutyRecord.EQUIPMENT_STATUS" placeholder="请选择" clearable>
                <el-option label="使用中" value="使用中" />
                <el-option label="故障中" value="故障中" />
              </el-select>
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">生产厂家：</label>
              <el-input type="text" v-model="newDutyRecord.EQUIPMENT_FACTORY" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">型号：</label>
              <el-input type="text" v-model="newDutyRecord.EQUIPMENT_MODEL" required />
            </div>

          </div>

        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addNewDutyRecord" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeAddDialog" style="width: 75px; height: 30px;">取消</el-button>

        </div>
      </form>
    </el-dialog>
    <!-- View Dialog -->

    <el-dialog width="700px" class="dialog-from" v-model="isViewDialogOpen" title="查看详情" destroy-on-close align-center
      :before-close="closeViewDialog">
      <div class="body-item">
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="box-content">
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">园区编码:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.PARK_CODE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">单位名称:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.COMPANY_NAME_2 }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">单位类型:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.COMPANY_TYPE == 0 ? '园区' : '企业' }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">姓名:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.PARK_WORKER_NAME }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">人员类型:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.WORKER_TYPE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">职位:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.ARK_WORKER_NAME }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">工号:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.PARK_WORKER_JOB_NUMBER }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">值班领导手机:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.LEADER_MOBILE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">值班领导电话:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.LEADER_PHONR }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">上岗时间:</span>
                <span class="auto-wrap">{{
                  dayjs(viewingDutyRecord.PARK_WORKER_WORK_TIME).format('YYYY-MM-DD HH:mm:ss')
                }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">离岗时间:</span>
                <span class="auto-wrap">{{
                  dayjs(viewingDutyRecord.PARK_WORKER_LEAVE_TIME).format('YYYY-MM-DD HH:mm:ss')
                }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">在岗状态:</span>
                <span class="auto-wrap">{{

                  viewingDutyRecord.PARK_WORKER_STATUS }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="19">
              <div>
                <span class="no-wrap">值班记录:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.WATCH_RECORDS }}</span>
              </div>
            </el-col>
            <el-col style="visibility: hidden;" :span="1">
              <div>
                <span class="no-wrap">预案编码:</span>
                <span class="auto-wrap">{{ viewingDutyRecord.EMERGENCE_PLAN_ID }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">

          <el-button @click="closeViewDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- Import Dialog -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <div class="mb-4">
        <label for="importFile" class="block text-sm font-medium">选择文件</label>
        <input type="file" id="importFile" @change="handleFileUpload" accept=".csv, .xlsx" class="mt-1 block w-full">
      </div>
      <div class="mt-4 flex justify-end space-x-2">
        <el-button @click="closeImportDialog"
          class="bg-secondary text-secondary-foreground px-4 py-2 rounded">取消</el-button>
        <el-button v-loading.fullscreen.lock="fullscreenLoading" @click="confirmImport"
          class="bg-accent text-accent-foreground px-4 py-2 rounded" type="primary">确认导入</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'

const { proxy } = getCurrentInstance()
import { exportData, checkval } from '#/utils/exportfile.js'
import { dayjs, ElLoading } from "element-plus"


const apiBaseUrl = ref(proxy.$currentUrl + '/api/public-equipment-information')

// 搜索相关
const search = ref({
  EQUIPMENT_CODE: '',
  EQUIPMENT_NAME: '',
  EQUIPMENT_TYPE: '',
  EQUIPMENT_STATUS: '',
})
const formItems = ref([
  {
    label: '设备编号：',
    model: 'EQUIPMENT_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '设备名称：',
    model: 'EQUIPMENT_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '设备类型：',
    model: 'EQUIPMENT_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '感知设备', value: '感知设备' },
      { label: '监测设备', value: '监测设备' },

    ],
  },
  {
    label: '设备状态：',
    model: 'EQUIPMENT_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '使用中', value: '使用中' },
      { label: '故障中', value: '故障中' },

    ],
  },
])
const loading = ref(false)
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const table = ref()

const rowKey = (row) => row.ID // 设置行的唯一标识
// 数据相关
const dutyRecords = ref([])
const allChecked = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])
// 对话框状态
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isEditing = ref(false)
const fullscreenLoading = ref(false)
// 新值班记录数据
const newDutyRecord = ref({

})

// 编辑和查看值班记录数据
const editingRecord = ref({
  employee_name: '',
  gender: '',
  duty_time: '',
  position: '',
  duty_status: '',
  contact_info: '',
  handover_record: ''
})
const viewingDutyRecord = ref({})

// 计算属性
const totalItems = computed(() => dutyRecords.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

const displayedDutyRecords = ref([])
const alltabledata = (data) => {
  displayedDutyRecords.value = data
}
// API 用函数
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const searchDutyRecords = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    dutyRecords.value = response.data.map(record => ({ ...record, checked: false }))
  } catch (error) {
    console.error('搜索失败:', error)
    alert('搜索失败')
  }
}

const addNewDutyRecord = async () => {


  if (checkval([
    'PARK_CODE',
    'COMPANY_CODE',
    'EQUIPMENT_NAME',
    'EQUIPMENT_LOCATION',
    'LONGITUDE',
    'LATITUDE',
    'EQUIPMENT_TYPE',
    'EQUIPMENT_STATUS',
    'EQUIPMENT_FACTORY',
    'EQUIPMENT_MODEL',
  ], '设备信息', newDutyRecord.value)) {
    return
  }




  // dayjs(newDutyRecord.value.PARK_WORKER_WORK_TIME).format('YYYY-MM-DD HH:mm:ss')
  // dayjs(newDutyRecord.value.PARK_WORKER_LEAVE_TIME).format('YYYY-MM-DD HH:mm:ss')
  newDutyRecord.value.COMPANY_TYPE = Number(newDutyRecord.value.COMPANY_TYPE)
  try {

    if (!isEditing.value) {
      await axios.post(apiBaseUrl.value, newDutyRecord.value)
      alert('创建成功')
    } else {
      await axios.put(`${apiBaseUrl.value}/${newDutyRecord.value.ID}`, newDutyRecord.value)
      alert('更新成功')
    }
    closeAddDialog()
    await searchDutyRecords()
  } catch (error) {
    console.error('创建失败:', error)
    alert('创建失败: ' + (error.response?.data?.message || error.message))
  }
}

const updateDutyRecord = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${editingRecord.value.id}`, editingRecord.value)
    alert(response.data.message || '更新成功')
    closeEditDialog()
    await searchDutyRecords()
  } catch (error) {
    console.error('更新失败:', error)
    alert('更新失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(async item => {
        await axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchDutyRecords()
    } catch (error) {
      console.error('删除失败:', error)
      alert('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 事件处理函数
const resetSearch = () => {
  search.value = {
    EQUIPMENT_CODE: '',
    EQUIPMENT_NAME: '',
    EQUIPMENT_TYPE: '',
    EQUIPMENT_STATUS: '',
  }
  searchDutyRecords()
}

const toggleAllCheckboxes = () => {
  dutyRecords.value.forEach(record => record.checked = allChecked.value)
}

const openAddDialog = () => {
  isAddDialogOpen.value = true

}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  newDutyRecord.value = {

  }
  isEditing.value = false
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
  console.log('Import dialog opened') // 添加日志
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed') // 添加日志
}

const importFile = ref(null)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
  console.log('File selected:', importFile.value.name) // 添加日志
}

const confirmImport = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    loading.close()
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await searchDutyRecords()
  } catch (error) {
    loading.close()
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

// const exportData = () => {
//   // 创建一个工作簿
//   const wb = XLSX.utils.book_new()

//   // 准备要导出的数据
//   const exportData = dutyRecords.value.map(record => ({
//     '值班人员姓名': record.employee_name,
//     '性别': record.gender,
//     '值班时间': record.duty_time,
//     '职务': record.position,
//     '值班状态': record.duty_status,
//     '联系方式': record.contact_info,
//     '交接记录': record.handover_record
//   }))

//   // 将数据转换为工作表
//   const ws = XLSX.utils.json_to_sheet(exportData)

//   // 将工作表添加到工作簿，并设置表名为"值班管理"
//   XLSX.utils.book_append_sheet(wb, ws, "值班管理")

//   // 生成二进制字符串
//   const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

//   // 将二进制字符串转换为 Blob
//   const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" })

//   // 创建下载链接
//   const link = document.createElement('a')
//   link.href = URL.createObjectURL(blob)
//   link.download = '值班管理.xlsx'

//   // 模拟点击下载
//   link.click()

//   // 释放 URL 对象
//   URL.revokeObjectURL(link.href)
// }

// 添加 s2ab 辅助函数
function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}

const editDutyRecord = (record) => {
  newDutyRecord.value = { ...record }
  isAddDialogOpen.value = true
  isEditing.value = true
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingRecord.value = {}
  console.log('Edit dialog closed') // 添加日志
}

const viewDetails = (record) => {
  viewingDutyRecord.value = { ...record }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingDutyRecord.value = {}
}

// 获取中文字段名
const getChineseFieldName = (key) => {
  const fieldNameMap = {
    employee_name: '值班人员姓名',
    gender: '性别',
    duty_time: '值班时间',
    position: '职务',
    duty_status: '值班状态',
    contact_info: '联系方式',
    handover_record: '交接记录'
  }
  return fieldNameMap[key] || key
}

// 生命周期钩子
onMounted(() => {
  searchDutyRecords()
})
</script>

<style scoped>
.action-button {
  @apply text-primary hover:text-primary/80 px-2 py-1 rounded;
}
</style>


